package com.cskaoyan.typehandler;

import com.cskaoyan.utils.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ListStringArrayTypeHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        if (strings == null) {
            return ;
        }
        String string = strings.toString();
        String substring = string.substring(1, string.length() - 1);
        preparedStatement.setString(i,substring);

    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        if (!s.contains("-")) {
            List<String> strings = new ArrayList<>();
            strings.add(s);
            return strings;
        }
        String string = resultSet.getString(s);
        return getStringList(string);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {

        String string = resultSet.getString(i);
        return getStringList(string);
    }



    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {

        String string = callableStatement.getString(i);
        return getStringList(string);
    }


    private List<String> getStringList(String string) {

        String substring = string.substring(1, string.length() - 1);
        String[] split = substring.split(",");
        return Arrays.asList(split);
    }
}
